﻿/*
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#include "account-information.h"
#include "app-manager.h"

#include <QDebug>
#include <QProcess>
#include <QDBusReply>

#define DEFAULT_USER_ICON_FILE        ":/icon/default-community-image.png"
#define KYLIN_POWER_NORMAL_PATH_MAJOR ":/icon/pad_mainpower.svg"

#define ADMINISTRATORS 1
#define STANDARD_USER  0

using namespace UkuiShortcut;

AccountInformation::AccountInformation(QObject *parent) : QObject(parent)
{
    initMemberVariable();
    registeredAccountsDbus();
    initUserInfo();
}

AccountInformation::~AccountInformation()
= default;

void AccountInformation::initMemberVariable()
{
    m_administrator = QObject::tr("administrators");
    m_standardUser = QObject::tr("standard users");
}

void AccountInformation::registeredAccountsDbus()
{
    m_systemUserIFace = new QDBusInterface("org.freedesktop.Accounts",
                                           "/org/freedesktop/Accounts",
                                           "org.freedesktop.Accounts",
                                           QDBusConnection::systemBus(), this);
}

void AccountInformation::initUserInfo()
{
    QStringList objectPaths = getUserObjectPath();
    UserInformation user;

    for (const QString& objectPath : objectPaths){
        user = GetUserInformation(objectPath);
        if(user.current && user.isLogged) {
            m_currentUserInfo = user;
            m_currentUserIFace = new QDBusInterface("org.freedesktop.Accounts",
                                                    objectPath,
                                                    "org.freedesktop.DBus.Properties",
                                                    QDBusConnection::systemBus(), this);

            m_currentUserIFace->connection().connect("org.freedesktop.Accounts", objectPath,
                                                     "org.freedesktop.DBus.Properties", "PropertiesChanged",
                                                     this, SLOT(currentAccountUpdateSlot(QString, QMap<QString, QVariant>, QStringList)));

            break;
        }
    }
}

QStringList AccountInformation::getUserObjectPath()
{
    QStringList users;

    QDBusReply<QList<QDBusObjectPath> > reply = m_systemUserIFace->call("ListCachedUsers");
    if (reply.isValid()) {
        for (const QDBusObjectPath& op : reply.value()) {
            users << op.path();
        }
    }

    return users;
}

UserInformation AccountInformation::GetUserInformation(const QString& objectPath)
{
    UserInformation user;

    //默认值
    user.current = false;
    user.isLogged = false;
    user.autologin = false;

    QDBusInterface userInterface("org.freedesktop.Accounts",
                                 objectPath,
                                 "org.freedesktop.DBus.Properties",
                                 QDBusConnection::systemBus());

    QDBusReply<QMap<QString, QVariant> > reply = userInterface.call("GetAll", "org.freedesktop.Accounts.User");
    if (reply.isValid()) {
        QMap<QString, QVariant> propertyMap;
        propertyMap = reply.value();
        user.username = propertyMap.find("UserName").value().toString();
        user.realName = propertyMap.find("RealName").value().toString();
        user.accountType = propertyMap.find("AccountType").value().toInt();
        user.iconFile = propertyMap.find("IconFile").value().toString();
        user.passwdType = propertyMap.find("PasswordMode").value().toInt();
        user.uid = propertyMap.find("Uid").value().toInt();
        user.autologin = false;
        user.objPath = objectPath;

        if (user.username == QString(qgetenv("USER"))) {
            user.current = true;
            user.isLogged = true;
        }
    } else {
        qDebug() << "GetUserInformation: reply failed";
    }

    return user;
}

void AccountInformation::currentAccountUpdateSlot(const QString& property, const QMap<QString, QVariant>& propertyMap,
                                                  const QStringList& propertyList)
{
    Q_UNUSED(property)
    Q_UNUSED(propertyList)
    QStringList keys = propertyMap.keys();

    if (keys.contains("IconFile")) {
        m_currentUserInfo.iconFile = propertyMap.value("IconFile").toString();
    }

    if (keys.contains("UserName")) {
        m_currentUserInfo.username = propertyMap.value("UserName").toString();
    }

    if (keys.contains("RealName")) {
        m_currentUserInfo.realName = propertyMap.value("RealName").toString();
    }

    if (keys.contains("AccountType")) {
        m_currentUserInfo.accountType = propertyMap.value("AccountType").toInt();
    }

    Q_EMIT userInfoChanged();
}

QString AccountInformation::getUsername()
{
    return m_currentUserInfo.username;
}

QString AccountInformation::getRealName()
{
    return m_currentUserInfo.realName;
}

QString AccountInformation::getIconFile()
{
    if (m_currentUserInfo.iconFile.isEmpty()) {
        return {DEFAULT_USER_ICON_FILE};
    }

    return m_currentUserInfo.iconFile;
}

QString AccountInformation::getAccountType()
{
    if (m_currentUserInfo.accountType == ADMINISTRATORS) {
        return m_administrator;
    }

    if (m_currentUserInfo.accountType == STANDARD_USER) {
        return m_standardUser;
    }

    return "";
}

void AccountInformation::openUserCenter()
{
    QStringList args;
    args.append("-m");
    args.append("Userinfo");

    if (Sidebar::AppManager::getInstance(this)->LaunchAppWithArguments("ukui-control-center", args)) {
        qDebug() << "open control-center with appmanager.";
        return;
    }

    qWarning() << "AppManagerDbus is invalid，open with QProcess";
    QProcess::startDetached("ukui-control-center -m Userinfo");
}

PowerButton::PowerButton(QObject *parent) : QObject(parent)
{

}

PowerButton::~PowerButton()
= default;

QString PowerButton::getIcon()
{
    return {KYLIN_POWER_NORMAL_PATH_MAJOR};
}

QString PowerButton::getToolTip()
{
    return {tr("power")};
}

QColor PowerButton::baseColor()
{
    return {"#FFE9E6"};
}

QColor PowerButton::highLightColor()
{
    return {"#FF8D8D"};
}

void PowerButton::clicked()
{
    if(!Sidebar::AppManager::getInstance(this)->LaunchApp("ukui-session-tools.desktop")) {
        qWarning()<<"AppManagerDbus is invalid，open with QProcess";
        QProcess::startDetached("ukui-session-tools");
    } else {
        qDebug() << "open ukui-session-tools with appmanager.";
    }
}
